# To change this template, choose Tools | Templates
# and open the template in the editor.

__author__="jonathan"
__date__ ="$24-May-2010 20:37:00$"

import pygame
import rabbyt
from os.path import join as join_path

TEX_CACHE = {}

def pygame_tex_shape():
    """The tex_shape argument to rabbyt.Sprite.__init__()."""
    return (0, 0, 1, 1)

class Sprite(rabbyt.Sprite):

    images_directory = 'images'
    
    def __init__(self):
        super(Sprite, self).__init__(tex_shape=pygame_tex_shape())
        self.textures = []
        self.num_textures = 0

    def _load_texture(self, name):
        """Load the textures and set the shape. Assumes a uniform texture
        size for all images."""
        if name not in TEX_CACHE:
            file_name = join_path(Sprite.images_directory, name)
            TEX_CACHE[name] = rabbyt.autodetect_load_texture(file_name)

        (tex_id, tex_size) = TEX_CACHE[name]

        self.textures.append(tex_id)
        # This if block ripped from rabbyt.Sprite._set_texture().
        if tex_size:
            w, h = tex_size
            self.shape = [-w/2, h/2, w/2, -h/2]
        self.num_textures += 1


class FixedSprite(Sprite):
    """FixedSprite represents a fixed image viewable from only one direction.

    The geometry is 2D. Use its bounds like a regular Pygame sprite.

    The image is isometric. Set the sprite's xy attribute to the return
    value of iso.to_isometric() to translate its 2D position to
    isometric space."""

    def __init__(self, name, size, pos, zorder):
        super(type(self), self).__init__()

        self._load_texture(name + '.png')
        self.texture_id = self.textures[0]
        self.rect = pygame.Rect(((0, 0), size))
        self.pos = pos
        self.zorder = zorder

    def update(self, view):
        pos = view.to_view((self.pos,))[0][:2]
        self.left = pos[0]
        self.top = pos[1]
        self.render()


class IsoSprite(Sprite):
    """32-way isometric sprite."""

    file_name = '%04d.png'

    def __init__(self, name, pos, scale=0.25):
        super(type(self), self).__init__()
        self.scale = scale
        self.name = name
        self.textures = []
        self.pos = pos
        for i in xrange(1, 33):
            self._load_texture(join_path(name, name + IsoSprite.file_name % i))
        self.angle = 0

    def update(self, view):
        """Set image according to angle. Any angle is permissible."""
        self.xy = view.to_view((self.pos,))[0][:2]
        i = int((self.angle % 360)/360.0 * self.num_textures)
        self.texture_id = self.textures[i]
